package cn.iocoder.yudao.module.erp.service.product;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.collection.MapUtils;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.erp.controller.admin.pristock.vo.PriStockRespVO;
import cn.iocoder.yudao.module.erp.controller.admin.product.vo.product.ErpProductPageReqVO;
import cn.iocoder.yudao.module.erp.controller.admin.product.vo.product.ErpProductRespVO;
import cn.iocoder.yudao.module.erp.controller.admin.product.vo.product.ProductSaveReqVO;
import cn.iocoder.yudao.module.erp.controller.admin.purchase.vo.supplier.ErpSupplierPageReqVO;
import cn.iocoder.yudao.module.erp.controller.admin.relationship.vo.RelationshipPageReqVO;
import cn.iocoder.yudao.module.erp.controller.admin.relationship.vo.RelationshipSaveReqVO;
import cn.iocoder.yudao.module.erp.dal.dataobject.departquantity.DepartQuantityDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.product.ErpProductCategoryDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.product.ErpProductDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.product.ErpProductUnitDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.relationship.RelationshipDO;
import cn.iocoder.yudao.module.erp.dal.mysql.product.ErpProductMapper;
import cn.iocoder.yudao.module.erp.dal.mysql.relationship.RelationshipMapper;
import jakarta.annotation.Resource;
import org.dromara.hutool.core.lang.page.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.*;
import static cn.iocoder.yudao.module.erp.enums.ErrorCodeConstants.*;

/**
 * ERP 产品 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class ErpProductServiceImpl implements ErpProductService {

    @Resource
    private ErpProductMapper productMapper;

    @Resource
    private ErpProductCategoryService productCategoryService;
    @Resource
    private ErpProductUnitService productUnitService;

    @Resource
    private RelationshipMapper relationshipMapper;

    @Override
    public Long createProduct(ProductSaveReqVO createReqVO) {
        // TODO 芋艿：校验分类
        // 插入
        ErpProductDO product = BeanUtils.toBean(createReqVO, ErpProductDO.class);
        productMapper.insert(product);
        RelationshipSaveReqVO createRelaVO = new RelationshipSaveReqVO();
        createRelaVO.setProductId(createReqVO.getId());
        createRelaVO.setSupplierId(createReqVO.getSupplierId());
        createRelaVO.setSort(1);
        RelationshipDO relationship = BeanUtils.toBean(createRelaVO, RelationshipDO.class);
        relationshipMapper.insert(relationship);
        // 返回
        return product.getId();
    }

    @Override
    public void updateProductPrice(Long dataId, BigDecimal purchasePrice) {
        // 校验存在
        validateProductExists(dataId);
        LocalDateTime now = LocalDateTime.now();
//        更新截止日期为今天  价格为历史价格
        productMapper.updateProductPrice(dataId,now);
//        新增一条数据
        ErpProductDO source =  productMapper.selectById(dataId);
        source.setPurchasePrice(purchasePrice);
        source.setDataId(null);
        source.setStartTime(now);
        source.setEndTime(LocalDateTime.parse("2099-12-31T23:59:59"));
        source.setCreateTime(now);
        productMapper.insert(source);
    }

    @Override
    public void updateProduct(ProductSaveReqVO updateReqVO) {
        // TODO 芋艿：校验分类
        // 校验存在
        validateProductExists(updateReqVO.getDataId());
        ErpProductDO product = BeanUtils.toBean(updateReqVO, ErpProductDO.class);
//        Long id = updateReqVO.getDataId();
//        ErpProductDO Source =  productMapper.selectById(id);
//        LocalDateTime now = LocalDateTime.now();
//        Source.setEndTime(now);
        // 更新
        productMapper.updateById(product);
//        ErpProductDO product = BeanUtils.toBean(updateReqVO, ErpProductDO.class);
//        product.setDataId(null);
//        product.setStartTime(now);
//        product.setEndTime(LocalDateTime.parse("2099-12-31T23:59:59"));
//        productMapper.insert(product);
        productMapper.deleteRelationship(updateReqVO.getId());
        RelationshipSaveReqVO createRelaVO = new RelationshipSaveReqVO();
        createRelaVO.setProductId(updateReqVO.getId());
        createRelaVO.setSupplierId(updateReqVO.getSupplierId());
        createRelaVO.setSort(1);
        RelationshipDO relationship = BeanUtils.toBean(createRelaVO, RelationshipDO.class);
        relationshipMapper.insert(relationship);

    }

    @Override
    public void deleteProduct(Long id) {
        // 校验存在
        validateProductExists(id);
        int isDelete = 1;
        // 删除
        productMapper.logicallyDeleteById(id,isDelete);
    }

    @Override
    public List<ErpProductDO> validProductList(Collection<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            return Collections.emptyList();
        }
        List<ErpProductDO> list = productMapper.selectBatchIds(ids);
        Map<Long, ErpProductDO> productMap = convertMap(list, ErpProductDO::getId);
        for (Long id : ids) {
            ErpProductDO product = productMap.get(id);
            if (productMap.get(id) == null) {
                throw exception(PRODUCT_NOT_EXISTS);
            }
            if (CommonStatusEnum.isDisable(product.getStatus())) {
                throw exception(PRODUCT_NOT_ENABLE, product.getName());
            }
        }
        return list;
    }

    private void validateProductExists(Long id) {
        if (productMapper.selectById(id) == null) {
            throw exception(PRODUCT_NOT_EXISTS);
        }
    }

    @Override
    public ErpProductDO getProduct(Long id) {
        return productMapper.selectById(id);
    }

    @Override
    public ErpProductDO getQuantity(Long id) {
        ErpProductDO ep =productMapper.selectByIdStartTime(id);
        DepartQuantityDO dq = productMapper.getDepart(id);
        if(null != dq){
            ep.setQuantityCount(dq.getQuantityCount());
            ep.setTaskStartTime(dq.getTaskStartTime());
            ep.setTaskEndTime(dq.getTaskEndTime());
            ep.setAllocationStatus(dq.getAllocationStatus());
        }
        return ep;
    }

    @Override
    public List<ErpProductRespVO> getProductVOListByStatus(Integer status) {
        List<ErpProductDO> list = productMapper.selectListByStatus(status);
        return buildProductVOList(list);
    }

    /**
     * 产品名称筛选框查询方法
     * @param status
     * @param params
     * @return
     */
    @Override
    public List<ErpProductRespVO> getProductVOLists(Integer status,String params) {
        //参数拼接%用于模糊查询
        String like ="%"+params+"%";
        return productMapper.selectLists(status,like);
    }

    @Override
    public PageResult<ErpProductDO> getProductToget(Integer status,String params,Integer page,Integer pageSize) {
        PageResult<ErpProductDO> result =new PageResult<>();
        int pages = (page-1)*pageSize;
        //参数拼接%用于模糊查询
        String like ="%"+params+"%";
        List<ErpProductDO> finalyList = productMapper.getProductToget(status,like,pages,pageSize);
        int total = productMapper.selectTotalfrom(like);
        result.setList(finalyList);
        result.setTotal((long) total);
        return result;
    }

    @Override
    public List<ErpProductRespVO> getProductVOLists(Integer status,String params,Integer[] ids) {
        //参数拼接%用于模糊查询
        String like ="%"+params+"%";
        return productMapper.selectListBySec(status,like,ids);
    }


    @Override
    public List<ErpProductRespVO> getProductVOList(Collection<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            return Collections.emptyList();
        }
        List<ErpProductDO> list = productMapper.selectBatchIds(ids);
        return buildProductVOList(list);
    }

    @Override
    public PageResult<ErpProductRespVO> getProductVOPage(ErpProductPageReqVO pageReqVO) {
        PageResult<ErpProductDO> pageResult = productMapper.selectPage(pageReqVO);
        List<PriStockRespVO> dp  = new ArrayList<>();
        for(ErpProductDO ep:pageResult.getList() ){
            PriStockRespVO priStockRespVO =  productMapper.selectPri(ep.getId());
            if(null != priStockRespVO){
                dp.add(priStockRespVO);
            }
        }

        for(int i = 0;i<dp.size();i++){
            if(dp.get(i).getProductId().toString().equals(pageResult.getList().get(i).getId().toString())){
                pageResult.getList().get(i).setQuantityCount(dp.get(i).getQuantityCount());
                pageResult.getList().get(i).setAllocationStatus(dp.get(i).getAllocationStatus());
            };
        }

        return new PageResult<>(buildProductVOList(pageResult.getList()), pageResult.getTotal());
    }

    @Override
    public PageResult<ErpProductDO> getProductPags(ErpProductPageReqVO pageReqVO) {
        int page = (pageReqVO.getPageNo()-1)*pageReqVO.getPageSize();
        pageReqVO.setPageNo(page);
        List<ErpProductDO> pageResult = productMapper.selectPages(pageReqVO);
        int total = productMapper.total(pageReqVO);
        List<PriStockRespVO> dp  = new ArrayList<>();
        for(ErpProductDO ep:pageResult){
            PriStockRespVO priStockRespVO =  productMapper.selectPri(ep.getId());
            if(null != priStockRespVO){
                dp.add(priStockRespVO);
            }
        }
        for(int i = 0;i<dp.size();i++){
            if(dp.get(i).getProductId().toString().equals(pageResult.get(i).getId().toString())){
                pageResult.get(i).setQuantityCount(dp.get(i).getQuantityCount());
                pageResult.get(i).setAllocationStatus(dp.get(i).getAllocationStatus());
            };
        }
        PageResult<ErpProductDO> result =new PageResult<>();
        result.setList(pageResult);
        result.setTotal((long) total);
        return result;
    }

    @Override
    public PageResult<ErpProductDO> getProductPagsForRelation(ErpProductPageReqVO pageReqVO) {
        int page = (pageReqVO.getPageNo()-1)*pageReqVO.getPageSize();
        pageReqVO.setPageNo(page);
        List<ErpProductDO> finalyList = new ArrayList<>();
        List<ErpProductDO> pageResult = productMapper.getProductPagsForRelation(pageReqVO);
        List<Long>productId = new ArrayList<>();
        for(ErpProductDO prodId : pageResult){
            productId.add(prodId.getId());
        }
        int total = productMapper.total(pageReqVO);
        List<RelationshipDO> dp  = productMapper.getRelationShip(productId);
        PageResult<ErpProductDO> result =new PageResult<>();
        if(dp!=null){
            for(ErpProductDO epdo:pageResult) {
                if(dp.size()==0){
                    epdo.setIsHooking(0);
                }else{
                    for(RelationshipDO rsdo:dp){

                        if (epdo.getId().equals(rsdo.getProductId())) {
                            epdo.setIsHooking(1);
                            break;
                        } else {
                            epdo.setIsHooking(0);
                        }
                    }
                }
                finalyList.add(epdo);
            }
        }
        result.setList(finalyList);
        result.setTotal((long) total);
        return result;
    }


    private List<ErpProductRespVO> buildProductVOList(List<ErpProductDO> list) {
        if (CollUtil.isEmpty(list)) {
            return Collections.emptyList();
        }
        Map<Long, ErpProductCategoryDO> categoryMap = productCategoryService.getProductCategoryMap(
                convertSet(list, ErpProductDO::getCategoryId));
        Map<Long, ErpProductUnitDO> unitMap = productUnitService.getProductUnitMap(
                convertSet(list, ErpProductDO::getUnitId));
        return BeanUtils.toBean(list, ErpProductRespVO.class, product -> {
            MapUtils.findAndThen(categoryMap, product.getCategoryId(),
                    category -> product.setCategoryName(category.getName()));
            MapUtils.findAndThen(unitMap, product.getUnitId(),
                    unit -> product.setUnitName(unit.getName()));
        });
    }

    @Override
    public Long getProductCountByCategoryId(Long categoryId) {
        return productMapper.selectCountByCategoryId(categoryId);
    }

    @Override
    public Long getProductCountByUnitId(Long unitId) {
        return productMapper.selectCountByUnitId(unitId);
    }

    @Override
    public PriStockRespVO selectPri(Long ids) {
        return productMapper.selectPri(ids);
    }




}